<template>
  <div class="admin-page admin-student-registration">
    <div class="page-header">
      <h1>学籍管理</h1>
      <div class="actions">
        <el-button type="primary" @click="openStudentDialog(null)">
          <el-icon><Plus /></el-icon> 新增学生
        </el-button>
        <el-button type="info" @click="downloadTemplate">
          <el-icon><Download /></el-icon> 下载导入模板
        </el-button>
        <el-button type="success" @click="openImportDialog">
          <el-icon><Upload /></el-icon> 批量导入
        </el-button>
      </div>
    </div>
    
    <el-card class="table-card">
      <!-- 学生搜索过滤组件 -->
      <StudentSearchForm
        v-model="filters"
        :lc-classes="lcClasses"
        :majors="majors"
        :cengcis="cengCis"
        :student-statuses="studentStatuses"
        @search="searchStudents"
        @reset="resetFilters"
        @update:model-value="updateFilters"
      />
      
      <!-- 学生表格组件 -->
      <StudentDataTable
        :students="students"
        :loading="loading"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.current"
        @edit="openStudentDialog"
        @status-change="openStatusDialog"
        @delete="deleteStudent"
        @row-click="handleRowClick"
        @page-change="handlePageChange"
      />
    </el-card>
    
    <!-- 学生表单对话框组件 -->
    <StudentEditDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :student="currentStudent"
      :lc-classes="lcClasses"
      :majors="majors"
      :ceng-cis="cengCis"
      :student-statuses="studentStatuses"
      @submit="submitStudentForm"
    />
    
    <!-- 状态修改对话框组件 -->
    <StudentStatusDialog
      v-model="statusDialogVisible"
      :student="currentStudent"
      :student-statuses="studentStatuses"
      @submit="submitStatusChange"
    />
    
    <!-- 导入对话框组件 -->
    <StudentImportDialog
      v-model="importDialogVisible"
      :importing="importing"
      @submit="submitImport"
      @download-template="downloadTemplate"
    />
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { studentApi } from '@/api/student'
import { classApi, majorApi, cengCiApi, studentStatusApi } from '@/api/base-data'
import { Plus, Upload, Download } from '@element-plus/icons-vue'

// 导入子组件
import StudentSearchForm from '@/components/student/StudentSearchForm.vue'
import StudentDataTable from '@/components/student/StudentDataTable.vue'
import StudentEditDialog from '@/components/student/StudentEditDialog.vue'
import StudentStatusDialog from '@/components/student/StudentStatusDialog.vue'
import StudentImportDialog from '@/components/student/StudentImportDialog.vue'

export default {
  components: {
    Plus, Upload, Download,
    StudentSearchForm,
    StudentDataTable,
    StudentEditDialog,
    StudentStatusDialog,
    StudentImportDialog
  },
  setup() {
    // 数据加载状态
    const loading = ref(false)
    
    // 学员列表数据
    const students = ref([])
    
    // 下拉选项数据
    const lcClasses = ref([])
    const majors = ref([])
    const cengCis = ref([])
    const studentStatuses = ref([])
    
    // 过滤条件
    const filters = reactive({
      studentId: '',
      name: '',
      classId: '',
      majorId: '',
      cengciId: '',
      statusId: ''
    })

    // 分页数据
    const pagination = ref({
      current: 1,
      pageSize: 10,
      total: 0
    })
    
    // 对话框状态
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const currentStudent = ref(null)
    const statusDialogVisible = ref(false)
    const importDialogVisible = ref(false)
    const importing = ref(false)

    // 获取学员列表（使用后台分页）
    const fetchStudents = async () => {
      loading.value = true
      try {
        // 构建查询参数，包括分页和过滤条件
        const params = {
          page: pagination.value.current - 1, // 后台从0开始
          size: pagination.value.pageSize
        }
        
        // 添加过滤条件
        if (filters.studentId) params.studentId = filters.studentId
        if (filters.name) params.name = filters.name
        if (filters.classId) params.classId = filters.classId
        if (filters.majorId) params.majorId = filters.majorId
        if (filters.cengciId) params.cengciId = filters.cengciId
        if (filters.statusId) params.statusId = filters.statusId
        
        const res = await studentApi.getAllStudents(params)
        
        // 处理分页响应
        if (res && res.content) {
          students.value = res.content || []
          pagination.value.total = res.totalElements || 0
        } else {
          students.value = res || []
          pagination.value.total = students.value.length
        }
        
        loading.value = false
      } catch (error) {
        ElMessage.error('获取学员列表失败')
        loading.value = false
      }
    }

    // 获取所有下拉选项数据
    const fetchOptions = async () => {
      try {
        // 获取队次数据
        const classesRes = await classApi.getAllClasses()
        lcClasses.value = classesRes || []
        
        // 获取专业数据
        const majorsRes = await majorApi.getAllMajors()
        majors.value = majorsRes || []
        
        // 获取培养层次数据
        const cengCisRes = await cengCiApi.getAllCengCis()
        cengCis.value = cengCisRes || []
        
        // 获取学员状态数据
        const statusesRes = await studentStatusApi.getAllStudentStatuses()
        studentStatuses.value = statusesRes || []
      } catch (error) {
        ElMessage.error('获取下拉选项数据失败')
      }
    }

    // 打开学员表单对话框
    const openStudentDialog = (student) => {
      // 先设置当前学生数据，这会触发组件内部的表单重置和数据填充
      currentStudent.value = student;
      
      if (student) {
        dialogTitle.value = '编辑学员';
      } else {
        dialogTitle.value = '新增学生';
      }
      
      dialogVisible.value = true;
    };

    // 提交学生表单
    const submitStudentForm = async (formData) => {
      try {
        if (formData.id) {
          // 更新学生
          await studentApi.updateStudent(formData.id, formData)
          ElMessage.success('更新学生成功')
        } else {
          // 创建学生
          await studentApi.createStudent(formData)
          ElMessage.success('创建学生成功')
        }
        
        // 关闭对话框并刷新数据
        dialogVisible.value = false
        fetchStudents()
      } catch (error) {
        ElMessage.error(`提交学生表单失败: ${error.message || '未知错误'}`)
      }
    }

    // 删除学生
    const deleteStudent = (student) => {
      ElMessageBox.confirm(
        `确定要删除学生 ${student.name} (${student.studentId}) 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await studentApi.deleteStudent(student.id)
          ElMessage.success('删除学生成功')
          fetchStudents()
        } catch (error) {
          ElMessage.error(`删除学生失败: ${error.message || '未知错误'}`)
        }
      }).catch(() => {
        // 取消删除，不做任何操作
      })
    }

    // 打开状态修改对话框
    const openStatusDialog = (student) => {
      currentStudent.value = student
      statusDialogVisible.value = true
    }

    // 提交状态修改
    const submitStatusChange = async (statusData) => {
      try {
        await studentApi.updateStudentStatus(statusData.studentId, {
          statusId: statusData.statusId
        })
        ElMessage.success('修改学生状态成功')
        
        // 关闭对话框并刷新数据
        statusDialogVisible.value = false
        fetchStudents()
      } catch (error) {
        ElMessage.error(`修改学生状态失败: ${error.message || '未知错误'}`)
      }
    }

    // 搜索学生
    const searchStudents = async () => {
      loading.value = true
      try {
        // 过滤空值参数
        const searchParams = {}
        Object.keys(filters).forEach(key => {
          if (filters[key] !== '' && filters[key] !== null && filters[key] !== undefined) {
            searchParams[key] = filters[key]
          }
        })
        
        // 如果没有任何搜索条件，获取所有学生
        let res
        if (Object.keys(searchParams).length === 0) {
          res = await studentApi.getAllStudents()
        } else {
          res = await studentApi.getStudentsByFilter(searchParams)
        }
        
        console.log('搜索API响应:', res)
        
        // 处理分页响应
        if (res && res.content) {
          students.value = res.content || []
          pagination.value.total = res.totalElements || 0
        } else {
          students.value = res || []
          pagination.value.total = students.value.length
        }
        
        pagination.value.current = 1 // 重置页码
      } catch (error) {
        ElMessage.error('搜索学生失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }

    // 重置过滤器
    const resetFilters = () => {
      Object.keys(filters).forEach(key => {
        filters[key] = ''
      })
      searchStudents()
    }

    // 更新过滤器 - 处理v-model更新
    const updateFilters = (newFilters) => {
      console.log(`[DEBUG] updateFilters called with newFilters:`, newFilters)
      console.log(`[DEBUG] current filters before update:`, filters)
      
      // 使用Vue的响应式方式更新对象
      Object.keys(newFilters).forEach(key => {
        if (filters.hasOwnProperty(key)) {
          console.log(`[DEBUG] updating ${key} from "${filters[key]}" to "${newFilters[key]}"`)
          filters[key] = newFilters[key]
        }
      })
      
      console.log(`[DEBUG] filters after update:`, filters)
      
      // 强制触发响应式更新
      // 创建一个新的引用来确保Vue能够检测到变化
      const temp = { ...filters }
      Object.keys(temp).forEach(key => {
        filters[key] = temp[key]
      })
    }

    // 处理页码变化
    const handlePageChange = (page) => {
      pagination.value.current = page
      fetchStudents() // 重新获取数据
    }

    // 处理行点击
    const handleRowClick = (row) => {
      // 行点击处理
    }

    // 打开导入对话框
    const openImportDialog = () => {
      importDialogVisible.value = true
    }

    // 下载导入模板
    const downloadTemplate = () => {
      studentApi.downloadTemplate()
    }

    // 提交导入
    const submitImport = async (formData) => {
      if (!formData) {
        ElMessage.warning('请选择要导入的文件')
        return
      }
      
      importing.value = true
      
      try {
        const result = await studentApi.importStudents(formData)
        
        // 检查导入结果
        if (result && typeof result === 'object') {
          const { successCount = 0, errorCount = 0, total = 0, errors = [], reportFilePath } = result
          
          // 根据导入结果显示不同的消息
          let messageType = 'success'
          let messageText = ''
          
          if (errorCount === 0) {
            // 全部成功
            messageText = `导入成功！共导入 ${successCount} 条学生记录`
            messageType = 'success'
          } else if (successCount === 0) {
            // 全部失败
            messageText = `导入失败！共 ${errorCount} 条记录导入失败`
            if (errors.length > 0) {
              // 显示前3个错误信息
              const errorDetails = errors.slice(0, 3).map(err => 
                `第${err.row}行: ${err.message}`
              ).join('；')
              messageText += `\n错误详情：${errorDetails}`
              if (errors.length > 3) {
                messageText += `；还有${errors.length - 3}个错误...`
              }
            }
            messageType = 'error'
          } else {
            // 部分成功
            messageText = `导入完成！成功 ${successCount} 条，失败 ${errorCount} 条`
            if (errors.length > 0) {
              // 显示前3个错误信息
              const errorDetails = errors.slice(0, 3).map(err => 
                `第${err.row}行: ${err.message}`
              ).join('；')
              messageText += `\n失败详情：${errorDetails}`
              if (errors.length > 3) {
                messageText += `；还有${errors.length - 3}个错误...`
              }
            }
            messageType = 'warning'
          }
          
          // 显示消息，并添加下载报告的选项
          if (reportFilePath) {
            messageText += '\n\n点击确定下载详细导入报告'
            
            ElMessageBox.confirm(messageText, '导入结果', {
              confirmButtonText: '下载报告',
              cancelButtonText: '关闭',
              type: messageType === 'success' ? 'success' : messageType === 'error' ? 'error' : 'warning',
              showClose: true
            }).then(async () => {
              // 用户选择下载报告
              try {
                await studentApi.downloadImportReport(reportFilePath)
                ElMessage.success('报告下载成功')
              } catch (error) {
                ElMessage.error('下载报告失败: ' + (error.message || '未知错误'))
              }
            }).catch(() => {
              // 用户取消下载
            })
          } else {
            // 没有报告文件，直接显示消息
            if (messageType === 'success') {
              ElMessage.success(messageText)
            } else if (messageType === 'error') {
              ElMessage.error(messageText)
            } else {
              ElMessage.warning(messageText)
            }
          }
          
          // 只有在有成功记录时才关闭对话框和刷新数据
          if (successCount > 0) {
            importDialogVisible.value = false
            fetchStudents()
          }
        } else {
          // 兜底处理：如果返回结果格式不符合预期
          ElMessage.success('导入完成')
          importDialogVisible.value = false
          fetchStudents()
        }
      } catch (error) {
        ElMessage.error(`导入学生失败: ${error.message || '未知错误'}`)
      } finally {
        importing.value = false
      }
    }

    // 页面初始化
    onMounted(async () => {
      await fetchOptions()
      await fetchStudents()
    })
    
    return {
      loading,
      students,
      lcClasses,
      majors,
      cengCis,
      studentStatuses,
      filters,
      pagination,
      dialogVisible,
      dialogTitle,
      currentStudent,
      statusDialogVisible,
      importDialogVisible,
      importing,
      openStudentDialog,
      openStatusDialog,
      submitStudentForm,
      submitStatusChange,
      deleteStudent,
      searchStudents,
      resetFilters,
      updateFilters,
      handlePageChange,
      handleRowClick,
      openImportDialog,
      downloadTemplate,
      submitImport
    }
  }
}
</script>

<style scoped>
.admin-student-registration {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.actions {
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}
</style>